package com.activenetwork.custom.uielement.decorate;

import java.lang.reflect.Field;

import org.openqa.selenium.By;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class UIAnnotations {
    private Logger logger = LoggerFactory.getLogger(UIAnnotations.class);
	private Field field;

	public UIAnnotations(Field field) {
		this.field = field;
	}

	public By buildBy() {
		assertValidAnnotations();
		String pageName = field.getDeclaringClass().getSimpleName();		
		return IdentifierFactory.createBy(pageName, field.getName());
	}

	/**
	 * Use CacheLookup annotation in selenium framework
	 * 
	 * @return
	 */
	public boolean isLookupCached() {
		return (field.getAnnotation(CacheLookup.class) != null);
	}

	/**
	 * Verify one field should not be annotated by both @InJson and @FindBy/@FindBys
	 */
	private void assertValidAnnotations() {
		InJson inJson = field.getAnnotation(InJson.class);
		if (inJson != null) { // the field is annotated with @InJson
			FindBy findBy = field.getAnnotation(FindBy.class);
			FindBys findBys = field.getAnnotation(FindBys.class);
			if (findBy != null || findBys != null) {
				String msg = "If you use @InJson, you should not use @FindBy or @FindBys!";
				logger.error(msg);
				throw new IllegalArgumentException(msg);
			}
		}else{ // the field is not annotated with @InJson
			throw new RuntimeException("The field is not annotated by @InJson");
		}
	}

}
